//
//  userAccount.swift
//  kingWeiBo
//
//  Created by King on 15/9/13.
//  Copyright © 2015年 King. All rights reserved.
//

import UIKit

class userAccount: NSObject, NSCoding {
    
    /// 判断是否登录
    class var userLogin:Bool{
    
        return shareAccount != nil
    }
    
    ///
    var access_token:String?
    ///
    var expires_in:NSTimeInterval = 0 {
        didSet{
        
            expiresDate = NSDate(timeIntervalSinceNow: expires_in)
        }
    }
    ///
    var uid: String?
    
   ///过期日期
    var expiresDate: NSDate?
    
    /// 用户头像地址（大图），180×180像素
    var avatar_large: String?
    /// 友好显示名称
    var name: String?
    
    init(dict: [String: AnyObject]) {
        super.init()
        setValuesForKeysWithDictionary(dict)
        userAccount.UserAccount = self
    }
    override func setValue(value: AnyObject?, forUndefinedKey key: String) {}
    
    override var description: String {
    
        let preproties = ["access_token","expires_in","uid","expiresDate", "name", "avatar_large"]
        return  "\(dictionaryWithValuesForKeys(preproties))"
    }
    
    func loadUserInfo(finished:(error:NSError?)->()){
        NetWorkTool.shareTools.loadUserInfo(uid!) { (result, error) -> () in
            if error != nil{
                finished(error:error)
                return
            }
            self.name = result!["name"] as? String
            self.avatar_large = result!["avatar_large"] as? String
            self.saveAccount()
            finished(error: error)
        
    }
    }
    static private let accountPath = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true).last?.stringByAppendingString("/account.plist")
    func saveAccount(){
        NSKeyedArchiver.archiveRootObject(self, toFile: userAccount.accountPath!)
    }
    
    
    private static var UserAccount:userAccount?
    
    class var  shareAccount:userAccount?  {
//        if let account = NSKeyedUnarchiver.unarchiveObjectWithFile(accountPath!) as?
//        userAccount{
//            if account.expiresDate?.compare(NSDate()) == NSComparisonResult.OrderedDescending {
//            return account
//            }
//        }

        if UserAccount == nil {
            UserAccount = NSKeyedUnarchiver.unarchiveObjectWithFile(accountPath!) as? userAccount
            }
        
        if let date = UserAccount?.expiresDate where date.compare(NSDate()) ==  NSComparisonResult.OrderedAscending{
            UserAccount == nil
        }
        return UserAccount
    }
    /// 解档
    func encodeWithCoder(aCoder: NSCoder) {
        aCoder.encodeObject(access_token, forKey: "access_token")
        aCoder.encodeDouble(expires_in, forKey: "expires_in")
        aCoder.encodeObject(uid, forKey: "uid")
        aCoder.encodeObject(expiresDate, forKey: "expiresDate")
        aCoder.encodeObject(name, forKey: "name")
        aCoder.encodeObject(avatar_large, forKey: "avatar_large")
    }
    required init?(coder aDecoder: NSCoder) {
        access_token = aDecoder.decodeObjectForKey("access_token") as? String
        //TODO:Double
        expires_in = aDecoder.decodeDoubleForKey("expires_in")
        uid = aDecoder.decodeObjectForKey("uid") as? String
        expiresDate = aDecoder.decodeObjectForKey("expiresDate") as? NSDate
        name = aDecoder.decodeObjectForKey("name") as? String
        avatar_large = aDecoder.decodeObjectForKey("avatar_large") as? String
    }

}
